#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
主窗口界面
"""

from PyQt5.QtWidgets import (QMainWindow, QAction, QFileDialog, 
                             QMessageBox, QApplication, QTabWidget, QDialog)
from PyQt5.QtCore import Qt
from ui.import_dialog import ImportDialog
from ui.transaction_dialog import TransactionDialog
from ui.report_widget import ReportWidget
from ui.budget_widget import BudgetWidget
from ui.backup_widget import BackupWidget
from ui.transaction_widget import TransactionWidget
from ui.custom_classifier_dialog import CustomClassifierDialog
from database import Database


class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.db = Database()
        self.init_ui()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle('智能记账助手')
        self.setGeometry(100, 100, 1000, 700)
        
        # 创建菜单栏
        self.create_menu()
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        
        # 数据统计面板
        self.report_widget = ReportWidget()
        self.tab_widget.addTab(self.report_widget, "数据统计")
        
        # 交易明细面板
        self.transaction_widget = TransactionWidget()
        self.transaction_tab_index = self.tab_widget.addTab(self.transaction_widget, "交易明细")
        
        # 连接标签页切换信号，实现延迟加载
        self.tab_widget.currentChanged.connect(self.on_tab_changed)
        
        # 预算管理面板
        self.budget_widget = BudgetWidget()
        self.tab_widget.addTab(self.budget_widget, "预算管理")
        
        # 数据备份恢复面板
        self.backup_widget = BackupWidget()
        self.tab_widget.addTab(self.backup_widget, "数据备份")
        
        # 设置中心部件
        self.setCentralWidget(self.tab_widget)
        
        # 创建状态栏
        self.statusBar()
        
        # 显示欢迎信息
        self.statusBar().showMessage('欢迎使用智能记账助手')
        
    def create_menu(self):
        """创建菜单栏"""
        # 文件菜单
        file_menu = self.menuBar().addMenu('文件')
        
        # 导入菜单项
        import_action = QAction('导入', self)
        import_action.setShortcut('Ctrl+I')
        import_action.triggered.connect(self.import_data)
        file_menu.addAction(import_action)
        
        # 退出菜单项
        exit_action = QAction('退出', self)
        exit_action.setShortcut('Ctrl+Q')
        exit_action.triggered.connect(self.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = self.menuBar().addMenu('编辑')
        
        # 新建交易菜单项
        new_action = QAction('新建交易', self)
        new_action.setShortcut('Ctrl+N')
        new_action.triggered.connect(self.new_transaction)
        edit_menu.addAction(new_action)
        
        # 查看菜单
        view_menu = self.menuBar().addMenu('查看')
        
        # 刷新菜单项
        refresh_action = QAction('刷新', self)
        refresh_action.setShortcut('F5')
        refresh_action.triggered.connect(self.refresh_data)
        view_menu.addAction(refresh_action)
        
        # 数据管理菜单
        data_menu = self.menuBar().addMenu('数据')
        
        # 自定义分类训练器菜单项
        custom_classifier_action = QAction('自定义分类训练器', self)
        custom_classifier_action.triggered.connect(self.open_custom_classifier)
        data_menu.addAction(custom_classifier_action)
        
        # 清除所有数据菜单项
        clear_action = QAction('清除所有数据', self)
        clear_action.triggered.connect(self.clear_all_data)
        data_menu.addAction(clear_action)
        
    def import_data(self):
        """导入数据"""
        file_path, _ = QFileDialog.getOpenFileName(
            self, '选择账单文件', '', 'CSV files (*.csv);;Excel files (*.xlsx)')
            
        if file_path:
            dialog = ImportDialog(file_path, self)
            dialog.exec_()
            
    def new_transaction(self):
        """新建交易"""
        dialog = TransactionDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.statusBar().showMessage('交易记录已保存')
        
    def clear_all_data(self):
        """清除所有数据"""
        reply = QMessageBox.question(
            self, '确认清除', '确定要清除所有数据吗？此操作不可恢复！', 
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            
        if reply == QMessageBox.Yes:
            try:
                self.db.clear_all_data()
                self.statusBar().showMessage('所有数据已清除')
                # 刷新所有面板
                self.refresh_data()
            except Exception as e:
                QMessageBox.critical(self, '错误', f'清除数据时出错: {str(e)}')
    
    def refresh_data(self):
        """刷新数据"""
        try:
            # 更新所有标签页的数据
            self.report_widget.load_data()
            self.budget_widget.load_budgets()
            
            # 只有在交易明细标签页已经加载过数据时才刷新
            if hasattr(self, 'transaction_data_loaded') and self.transaction_data_loaded:
                self.transaction_widget.load_data()
            
            # 显示刷新成功消息
            self.statusBar().showMessage("数据已刷新", 2000)
        except Exception as e:
            QMessageBox.critical(self, "错误", f"刷新数据时出错: {str(e)}")
    
    def closeEvent(self, event):
        """关闭窗口事件"""
        reply = QMessageBox.question(
            self, '确认退出', '确定要退出智能记账助手吗？', 
            QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
            
        if reply == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()
            
    def open_custom_classifier(self):
        """打开自定义分类训练器"""
        dialog = CustomClassifierDialog(self)
        dialog.exec_()
        
    def on_tab_changed(self, index):
        """标签页切换事件"""
        # 如果切换到交易明细标签页且数据尚未加载，则加载数据
        if index == self.transaction_tab_index and not getattr(self, 'transaction_data_loaded', False):
            self.transaction_widget.load_data()
            self.transaction_data_loaded = True